<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\StockData;
use App\StockRightData;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{

    function index()
    {
        return view('index.index');
    }

    function downstock()
    {
        $StockData = new StockData();
        $startdate = date('Ymd', strtotime("-6 week"));
        $enddate = date('Ymd');
        $percent = -10;
        $stocks = $StockData->getStockMonthDown($startdate, $enddate, $percent);
        $stocks->map(function ($item) {
            $item['name'] = DB::table('stocks')->where('code', $item->code)->value('name');
        });
        return view('index.downstock', ['stocks' => $stocks, 'startdate' => $startdate, 'enddate' => $enddate, 'percent' => $percent]);
    }

    function historyData(Request $request, $code)
    {
        $data = StockData::where('code', $code)->orderBy('date', 'desc')->get();
        $stock = DB::table('stocks')->where('code', $code)->value('name');
        return view('index.historyData', ['data' => $data, 'code' => $code, 'stock' => $stock]);
    }

    function topstock(Request $request)
    {
        set_time_limit(0);
        $date = $request->input('date', date('Ymd', strtotime("-6 month")));
        $highprice = StockData::select('code', DB::raw('MAX(close) as close'))->where('date', '>', $date)->groupBy('code')->get()->toArray();
        $lastdate = StockData::orderBy('date', 'desc')->value('date');
        $stocks = StockData::select(['code', 'close'])->where([
            ['date', $lastdate],
            ['close', '<', '20']
        ])->get();
        $data = [];
        $stocks = $stocks->keyBy('code')->toArray();
        foreach ($highprice as $key => $val) {
            if (isset($stocks[$val['code']]['close'])) {
                $data[$val['code']]['highprice'] = $val['close'];
                $data[$val['code']]['newprice'] = $stocks[$val['code']]['close'];
                $data[$val['code']]['percent'] = round(($data[$val['code']]['highprice'] - $data[$val['code']]['newprice']) / $data[$val['code']]['highprice'] * 100, 2);
            }
        }
        $sort = collect($data)->sortByDesc('percent')->take(300)->toArray();
        foreach ($sort as $key => &$val) {
            $tmp = DB::table('stocks')->select(['name', 'industry'])->where('code', $key)->first();
            $val['name'] = $tmp->name;
            $val['industry'] = $tmp->industry;
        }
        return view('index.topstock', ['sort' => $sort]);


    }

    function rightstock(Request $request)
    {
        set_time_limit(0);
        $type = $request->type;
        $date = $request->input('date', date('Ymd', strtotime("-2 month")));
        if ($type == 'top') {
            $price = StockRightData::select('code', DB::raw('MAX(close) as close'))
									->where([
										['date', '>', $date],
										['code', 'not like', '3%'],
										['close', '>', 0],
									])
									->groupBy('code')
									->get()
									->toArray();
        } else {
            $price = StockRightData::select('code', DB::raw('MIN(close) as close'))
								->where([
										['code', 'not like', '3%'],
										['close', '>', 0],
									])
									->groupBy('code')
									->get()
									->toArray();
        }
        $lastdate = StockRightData::groupBy('date')
            ->havingRaw('COUNT(*) > 2500')
            ->orderBy('date', 'desc')
            ->limit(1)
            ->value('date');

        $stocks = StockRightData::select(['code', 'close'])->where([
            ['date', $lastdate],
			['close', '>', '0'],
            ['close', '<', '20'],
			['code', 'not like', '3%'],
			['code', 'not like', '9%']
        ])->get();
        $data = [];
        $stocks = $stocks->keyBy('code')->toArray();
        foreach ($price as $key => $val) {
            if (isset($stocks[$val['code']]['close'])) {
                if ($type == 'top') {
                    $data[$val['code']]['highprice'] = $val['close'];
                    $data[$val['code']]['newprice'] = $stocks[$val['code']]['close'];
                    $data[$val['code']]['percent'] = sprintf('%.2f', ($data[$val['code']]['highprice'] - $data[$val['code']]['newprice']) / $data[$val['code']]['highprice'] * 100, 2);
                } else {
                    $data[$val['code']]['lowprice'] = $val['close'];
                    $data[$val['code']]['newprice'] = $stocks[$val['code']]['close'];
                    $data[$val['code']]['difference'] = sprintf('%.2f', $data[$val['code']]['newprice'] - $data[$val['code']]['lowprice']);
                }
            }
        }
		 if ($type == 'top') {
			$sort = collect($data)->sortByDesc('percent')->take(300)->toArray();
		   } else {
			  $sort = collect($data)->sortBy('difference')->take(300)->toArray();
		   }
        foreach ($sort as $key => &$val) {
            $tmp = DB::table('stocks')->select(['name', 'industry', 'timetoMarket', 'liquidAssets'])->where('code', $key)->first();
			if(isset($tmp)){
				$val['name'] = $tmp->name;
				$val['industry'] = $tmp->industry;
				$val['liquidAssets'] = sprintf('%.2f', $tmp->liquidAssets / 10000);
				$val['timetoMarket'] = substr($tmp->timetoMarket, 0, 4);
			}
         
        }
		$view = $type=='top' ? 'index.toprightstock' :'index.lowrightstock';
		//var_dump($sort);die;
        return view($view, ['sort' => $sort,'lastdate'=>$lastdate]);
       
    }


}
